package com.sinacom.ibuilding.service;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;


import com.ibatis.dao.client.DaoManager;
import com.sinacom.ibuilding.beans.Attach;
import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.News;
import com.sinacom.ibuilding.dao.DaoConfig;
import com.sinacom.ibuilding.dao.iface.NewsDao;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.Helper;
import com.sinacom.ibuilding.util.PageModel;

public class NewsService {
	
	private NewsDao newsDao;
	private TransActionService ts = new TransActionService();
	private IdCreateService idService = new IdCreateService();
	private MemberService memberService = new MemberService();
	public NewsService(){
		DaoManager	daoManager = DaoConfig.getDaoManager();
		newsDao = (NewsDao) daoManager.getDao(NewsDao.class);
	}
	
	public News getNewsById(String id){
		if(StringUtils.isEmpty(id)) return null;
		Map map = new HashMap(); 
	    map.put("id", id);
	    List list = newsDao.getNewsList(map);
	    if(list != null && list.size() > 0){
	    	News news = (News) list.get(0);
	    	List attachList = getAttachList(news.getId(), Constants.BELONG_TYPE_NEWS);
	    	news.setAttachList(attachList);
	    	return news;
	    }
	    return null;
	}
	
	public PageModel getNewsCategory(String category,Integer type,int page){
		if(StringUtils.isEmpty(category)) return null;
		int pageSize = 13;
	    Map map = new HashMap(); 
	    map.put("category", category);
	    map.put("type", type);
	    int startId = (page-1) * pageSize + 1; 
	    map.put("startId", new Integer(startId));
	    map.put("endId", new Integer(startId+pageSize));
	    List list = newsDao.getNewsList(map);
	    PageModel pageModel = new PageModel();
	    pageModel.setList(list);
	    pageModel.setCurrentPage(page);
	    pageModel.setPageSize(pageSize);
	    
	    int count = newsDao.getNewsListCount(map);
	    pageModel.setTotalRecord(count);
	    pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
	    return pageModel;
	}
	
	public List getIndexNewsCategory(String category,String type){
		Map map = new HashMap();
	    map.put("category", "('"+category+"')");
	    map.put("type", type);
	    map.put("startId", new Integer(1));
	    map.put("endId", new Integer(10));
	    List list = newsDao.getNewsList(map);
		return list;
	}
	
	/**
	 * 首页公告
	 * @return
	 */
	public List getIndexAnnounce(){
		Map map = new HashMap();
	    map.put("isAnnounce", new Boolean(true));
	    map.put("startId", new Integer(1));
	    map.put("endId", new Integer(4));
	    List list = newsDao.getNewsList(map);
		return list;
	}
	
	public void deleteAttach(String id){
	    if(StringUtils.isEmpty(id))return ;
	    Map map = new HashMap();
        map.put("id", id);
        newsDao.deleteAttach(map);
	}
	
	public void deleteAttach(String belongId,String belongType){
	    if(StringUtils.isEmpty(belongId))return ;
	    Map map = new HashMap();
        map.put("belongId", belongId);
        map.put("belongType", belongType);
        newsDao.deleteAttach(map);
	}
	
	public void insertAttach(Attach attach){
		newsDao.insertAttach(attach);
	}
	
	public List getAttachList(String belongId,int belongType){
		if(StringUtils.isEmpty(belongId) || belongType == 0)return null;
	    Map map = new HashMap();
        map.put("belongId", belongId);
        map.put("belongType", new Integer(belongType));
        return newsDao.getAttachList(map);
	}
	
	public boolean saveNews(Member member,News news){
		try{
			ts.startTransaction();
			if(news != null){
				
				news.setUpdater(member.getId());
			//	news.setCategory(member.getRole().getChargeRes());
				String attachs = news.getAttachs();
				JSONArray attachList = null;
				if(!StringUtils.isEmpty(attachs)){
					attachList = JSONArray.fromObject(attachs);
				}
				String id = null;
				if(StringUtils.isEmpty(news.getId())){
					id = String.valueOf(idService.generateId(Constants.TABLE_NEWS));
					news.setId(String.valueOf(id));
					news.setCreator(member.getId());
					newsDao.insertNews(news);
				}else{
					id = news.getId();
					newsDao.updateNews(news); 
					deleteAttach(id,String.valueOf(Constants.BELONG_TYPE_NEWS));
				}
				
				if(attachList != null && attachList.size() > 0){
					for (int j = 0; j < attachList.size(); j++) {
						JSONObject obj = attachList.getJSONObject(j);
						Attach attach = (Attach) JSONObject.toBean(obj, Attach.class);
						attach.setBelongId(String.valueOf(id));
						attach.setBelongType(new Integer(Constants.BELONG_TYPE_NEWS));
						attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
						insertAttach(attach);
					}
					
				}
				
				Boolean isShortmsg = news.getIsShortmsg(); 
//				如“短信通知”被勾选，发送短信到所有版块用户，内容为信息标题
				if(isShortmsg != null && isShortmsg.booleanValue()){
//					发布到有看这个版块权限的用户
				    List mlist = memberService.getCatgoryMember(news.getCategory());
				    if(mlist != null && mlist.size() > 0){
				        for (int i = 0; i < mlist.size(); i++) {
				            Member m = (Member) mlist.get(i);
				            if(!StringUtils.isEmpty(m.getMobile())){
	                            Helper.sendShortMsg(m.getMobile(), news.getTitle());
				            }
				        }
				    }
				    
				    
				}
			}
			ts.commitTransAction();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				ts.endTransAction();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		
		return true;
	}
	
	public void deleteNews(String newsId){
        if(StringUtils.isEmpty(newsId)) return ;
        Map map = new HashMap();
        map.put("id", newsId);
        try {
            ts.startTransaction();
            newsDao.deleteNews(map);
            deleteAttach(newsId,String.valueOf(Constants.BELONG_TYPE_NEWS));
            ts.commitTransAction();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                ts.endTransAction();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
	
	 public News getPreNews(String id, String category) {
		 Map map = new HashMap();
		 map.put("id", id);
		 map.put("category", category);
		return newsDao.getPreNews(map);
	}

    public News getNextNews(String id, String category) {
    	 Map map = new HashMap();
		 map.put("id", id);
		 map.put("category", category);
		return newsDao.getNextNews(map);
	}
	
	public static void main(String[] args){
		NewsService testService = new NewsService();
		TransActionService ts = new TransActionService();
		try {
            ts.startTransaction();
            testService.deleteAttach("111");
            ts.commitTransAction();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                ts.endTransAction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
		
		
	}

}
